/*
 * @Author: your name
 * @Date: 2024-03-27 18:48:59
 * @LastEditTime: 2024-03-27 18:58:26
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \.leetcode\203.移除链表元素.cpp
 */
/*
 * @lc app=leetcode.cn id=203 lang=cpp
 *
 * [203] 移除链表元素
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        // 申请一个虚拟头结点
        ListNode* dummy_node = new ListNode(-1);
        dummy_node->next = head;
        ListNode* current = dummy_node;
        while(current->next != nullptr){
            if(current->next->val == val){
                // 需要删除的节点
                ListNode* tmp = current->next;
                current->next = current->next->next;
                delete tmp;
            }
            else{
                current = current->next;
            }
        }
        ListNode* ans = dummy_node->next;
        delete dummy_node;
        return ans;
    }
};
// @lc code=end
// 加入一个虚拟节点比较好
